package com.tydic.mapboxtest;

import android.annotation.SuppressLint;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.camera.CameraPosition;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.constants.Style;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.MapboxMapOptions;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.plugins.locationlayer.LocationLayerMode;
import com.mapbox.mapboxsdk.plugins.locationlayer.LocationLayerPlugin;
import com.mapbox.services.android.telemetry.location.LocationEngine;
import com.mapbox.services.android.telemetry.location.LocationEngineListener;
import com.mapbox.services.android.telemetry.location.LocationEnginePriority;
import com.mapbox.services.android.telemetry.location.LocationEngineProvider;
import com.mapbox.services.android.telemetry.permissions.PermissionsListener;
import com.mapbox.services.android.telemetry.permissions.PermissionsManager;

import java.util.List;

/**
 * 测试MapBox定位
 */
public class LocationActivity extends AppCompatActivity implements LocationEngineListener,
        PermissionsListener {
    final private int REQUEST_CODE_ASK_PERMISSIONS = 123;

    RelativeLayout mRlContainer;

    MapView mMapView;
    MapboxMap mMapboxMap;


    private LocationEngine mLocationEngine;
    //    private LocationEngineListener mLocationEngineListener;
    private LocationLayerPlugin locationPlugin;
    private PermissionsManager permissionsManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Mapbox.getInstance(this, "pk" +
                ".eyJ1IjoiZ2FvamluMzM1IiwiYSI6ImNqZTVmOHF1ajA2OTMzM21ucnJ1NXFiMjQifQ" +
                ".Jkww19trUtLND31Uzcke0A");
        setContentView(R.layout.activity_location);

        mRlContainer = (RelativeLayout) findViewById(R.id.rl_root);

        MapboxMapOptions options = new MapboxMapOptions()
                .styleUrl(Style.MAPBOX_STREETS)
                .camera(new CameraPosition.Builder()
                        .target(new LatLng(38.905652, 100.604356))
                        .zoom(13)
                        .build());

        mMapView = new MapView(this, options);
        mMapView.onCreate(savedInstanceState);
        mRlContainer.addView(mMapView);


        // 获取定位引擎并激活
        mLocationEngine = new LocationEngineProvider(this).obtainBestLocationEngineAvailable();
        mLocationEngine.activate();

        mMapView.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(MapboxMap mapboxMap) {
                mMapboxMap = mapboxMap;

                enableLocationPlugin();
            }
        });
    }

    public void toggleGps(View view) {
        if (mMapboxMap != null) {
            if (mMapboxMap.isMyLocationEnabled()) {//已开启
                enableLocation();//若已开启，开始定位
            } else {//未开启
                if (PermissionsManager.areLocationPermissionsGranted(this)) {
                    enableLocation();
                } else {
                    /*ActivityCompat.requestPermissions(this, new String[]{Manifest.permission
                            .ACCESS_FINE_LOCATION}, REQUEST_CODE_ASK_PERMISSIONS);*/
                    permissionsManager = new PermissionsManager(this);
                    permissionsManager.requestLocationPermissions(this);
                }
            }
        }
    }

    // 设置定位
    @SuppressLint("MissingPermission")
    private void enableLocation() {
            //获取上次定位参数,如果存在先直接使用
            Location lastlocation = null;
            if (PermissionsManager.areLocationPermissionsGranted(this)) {
                lastlocation = mLocationEngine.getLastLocation();
            }
            if (lastlocation != null) {
                mMapboxMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng
                        (lastlocation), 16), 1000);
            }
            /*//连接到定位服务，不需要操作
            mLocationEngineListener = new LocationEngineListener() {
                @Override
                public void onConnected() {
                    //连接到定位服务，不需要操作
                }

                @Override
                public void onLocationChanged(Location location) {
                    if (location != null) {
                        mMapboxMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng
                                (location), 15), 1000);
                        mLocationEngine.removeLocationEngineListener(this);
                    }
                }
            };
            //设置监听器
            mLocationEngine.addLocationEngineListener(mLocationEngineListener);*/
            mLocationEngine.addLocationEngineListener(this);

        //添加或移除定位图层
//        mMapboxMap.setMyLocationEnabled(enable);
    }

    /*@SuppressLint("MissingPermission")
    @Override
    protected void onStart() {
        super.onStart();
        mMapView.onStart();
        if (mLocationEngine != null && mLocationEngineListener != null) {
            mLocationEngine.activate();
            if (PermissionsManager.areLocationPermissionsGranted(this)) {
                mLocationEngine.requestLocationUpdates();
            }
            mLocationEngine.addLocationEngineListener(mLocationEngineListener);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        mMapView.onStop();
        if (mLocationEngine != null && mLocationEngineListener != null) {
            mLocationEngine.removeLocationEngineListener(mLocationEngineListener);
            mLocationEngine.removeLocationUpdates();
            mLocationEngine.deactivate();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
        // Ensure no memory leak occurs if we register the location listener but the call hasn't
        // been made yet.
        if (mLocationEngineListener != null) {
            mLocationEngine.removeLocationEngineListener(mLocationEngineListener);
        }
    }*/

    @SuppressWarnings({"MissingPermission"})
    private void enableLocationPlugin() {
        // Check if permissions are enabled and if not request
        if (PermissionsManager.areLocationPermissionsGranted(this)) {
            // Create an instance of LOST location engine
            initializeLocationEngine();

            locationPlugin = new LocationLayerPlugin(mMapView, mMapboxMap, mLocationEngine);
            locationPlugin.setLocationLayerEnabled(LocationLayerMode.TRACKING);
        } else {
            permissionsManager = new PermissionsManager(this);
            permissionsManager.requestLocationPermissions(this);
        }
    }

    @SuppressWarnings({"MissingPermission"})
    private void initializeLocationEngine() {
        mLocationEngine = new LocationEngineProvider(this).obtainBestLocationEngineAvailable();
        mLocationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
        mLocationEngine.activate();

        Location lastLocation = mLocationEngine.getLastLocation();
        if (lastLocation != null) {
            setCameraPosition(lastLocation);
        } else {
            mLocationEngine.addLocationEngineListener(this);
        }
    }

    private void setCameraPosition(Location location) {
        mMapboxMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                new LatLng(location.getLatitude(), location.getLongitude()), 16));
    }

    @Override
    @SuppressWarnings({"MissingPermission"})
    public void onConnected() {
        mLocationEngine.requestLocationUpdates();
    }

    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            mLocationEngine.removeLocationEngineListener(this);
        }
    }

    @Override
    public void onExplanationNeeded(List<String> permissionsToExplain) {
        Toast.makeText(this, "This app needs location permissions in order to show its " +
                        "functionality.",
                Toast.LENGTH_LONG).show();
    }

    @Override
    public void onPermissionResult(boolean granted) {
        if (granted) {
            enableLocationPlugin();
        } else {
            Toast.makeText(this, "You didn\\'t grant location permissions.", Toast.LENGTH_LONG)
                    .show();
            finish();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    @SuppressWarnings({"MissingPermission"})
    protected void onStart() {
        super.onStart();
        if (locationPlugin != null) {
            locationPlugin.onStart();
        }
        mMapView.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mLocationEngine != null) {
            mLocationEngine.removeLocationUpdates();
        }
        if (locationPlugin != null) {
            locationPlugin.onStop();
        }
        mMapView.onStop();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
        if (mLocationEngine != null) {
            mLocationEngine.deactivate();
        }
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mMapView.onLowMemory();
    }
}
